<?php

namespace app\home\controller\Subject;

use app\common\controller\Home;
use think\Db;

class Subject extends Home
{
    protected $NoNeedLogin = ['index','info'];

    // 课程模型
    protected $SubjectModel = null;

    // 课程章节模型
    protected $ChapterModel = null;

    // 课程订单模型
    protected $OrderModel = null;

    // 用户模型
    protected $BusinessModel = null;

    // 消费记录模型
    protected $RecordModel = null;

    public function __construct()
    {
        parent::__construct();

        // 加载模型
        $this->SubjectModel = model('Subject.Subject');
        $this->ChapterModel = model('Subject.Chapter');
        $this->OrderModel = model('Subject.Order');
        $this->BusinessModel = model('Business.Business');
        $this->RecordModel = model('Business.Record');
    }
    
    public function index()
    {
        $keyword = $this->request->param('keywords','','trim');

        $where = [];

        if($keyword)
        {
            $where['title|content'] = ['like',"%$keyword%"];
        }

        $subjectList = $this->SubjectModel->where($where)->select();

        $this->assign([
            'subjectList' => $subjectList,
            'keyword' => $keyword
        ]);

        return $this->fetch();
    }

    public function info()
    {
        $subjectid = $this->request->param('subjectid',0,'trim');

        $subject = $this->SubjectModel->find($subjectid);

        if(!$subject)
        {
            $this->error('该课程不存在');
        }

        $ChapterList = $this->ChapterModel->where(['subid' => $subjectid])->select();

        /* 
            1、获取登录信息
            2、通过cookie去获取当前登录用户
            3、拿id跟likes进行比较
        */
        $LoginAuth = cookie('LoginAuth') ? cookie('LoginAuth') : [];

        $Busid = isset($LoginAuth['id']) ? $LoginAuth['id'] : 0;
        $BusMobile = isset($LoginAuth['mobile']) ? $LoginAuth['mobile'] : '';

        $where = [
            'id' => $Busid,
            'mobile' => $BusMobile
        ];

        $Business = model('Business.Business')->where($where)->find();

        // 点赞状态
        $like = false;

        if($Business)
        {
            $likeArr = explode(',',$subject['likes']);

            $likeArr = array_filter($likeArr);

            $like = in_array($Business['id'],$likeArr) ? true : false;
        }

        // 评价
        $commentList = $this->OrderModel->with(['business'])->where(['subid' => $subjectid,Db::raw('comment IS NOT NULL')])->select();
        

        // 模板赋值
        $this->assign([
            'subject' => $subject,
            'ChapterList' => $ChapterList,
            'like' => $like,
            'commentList' => $commentList
        ]);

        return $this->fetch();
    }

    // 播放
    public function play()
    {
        $subid = $this->request->param('subid',0,'trim');

        $listid = $this->request->param('listid',0,'trim');

        $subject = $this->SubjectModel->find($subid);

        if(!$subject)
        {
            $this->error('课程不存在');
        }

        // 查询订单里是否有该用户购买
        $where = [
            'subid' => $subid,
            'busid' => $this->LoginAuth['id']
        ];

        $order = $this->OrderModel->where($where)->find();

        if(!$order)
        {
            $this->error('请先购买课程',null,['buy' => 'buy']);
        }

        // 组装条件
        $where = [
            'subid' => $subid
        ];

        if($listid)
        {
            $where['id'] = $listid;
        }

        // 17:15 第一条视频 17:15:03 第二条视频
        $Chapter = $this->ChapterModel->where($where)->order('createtime ASC')->find();

        if(!$Chapter)
        {
            $this->error('该章节不存在');
        }

        $this->success('查询成功',null,$Chapter);
    }

    // 购买课程
    public function buy()
    {
        $subid = $this->request->param('subid',0,'trim');

        /* 
            查询课程是否存在
            查询是否已经购买了课程 提示不需重复
        */
        $subject = $this->SubjectModel->find($subid);

        // 如果课程不存在就会走进判断里
        if(!$subject)
        {
            $this->error('课程不存在');
        }

        $where = [
            'subid' => $subid,
            'busid' => $this->LoginAuth['id']
        ];

        $order = $this->OrderModel->where($where)->find();

        if($order)
        {
            $this->error('无须重复购买');
        }

        /* 
            subject_order 新增一条订单记录
            business 更新money的值
            business_record 新增一条用户消费记录
        */

        // 用户余额是否够购买课程
        $UpdateMoney = bcsub($this->LoginAuth['money'],$subject['price']);

        if($UpdateMoney < 0)
        {
            $this->error('余额不足，请及时充值');
        }

        // 开启事务
        /* 
            mysql事务：保证多条sql语句按顺序执行，如果其中某条sql语句执行失败，那么把前面已经执行成功的SQL回滚

            回滚 => 什么都没发生
        */

        $this->OrderModel->startTrans();
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();

        // 插入订单

        // 封装数据
        $OrderData = [
            'subid' => $subject['id'],
            'busid' => $this->LoginAuth['id'],
            'total' => $subject['price'],
            'code' => build_code('SU')
        ];

        $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);

        if($OrderStatus === FALSE)
        {
            $this->error($this->OrderModel->getError());
        }

        // 更新用户余额
        $BusinessData = [
            'id' => $this->LoginAuth['id'],
            'money' => $UpdateMoney
        ];

        $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

        if($BusinessStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->error('更新用户余额失败');
        }

        // 新增消费记录
        $RecordData = [
            'total' => $subject['price'],
            'content' => "你购买了{$subject['title']}课程,消费了{$subject['price']}",
            'busid' => $this->LoginAuth['id']
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

        if($RecordStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->BusinessModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        // 大判断
        if($OrderStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->error('购买课程失败');
        }else{
            $this->OrderModel->commit();
            $this->BusinessModel->commit();
            $this->RecordModel->commit();
            $this->success('购买课程成功');
        }
    }

    // 点赞|取消点赞
    public function like()
    {
        $subjectid = $this->request->param('subid',0,'trim');

        /* 
            根据课程id查询出来该课程 -> like字段 -> 字符串 转成 数组 => in_array
        */

        $subject = $this->SubjectModel->find($subjectid);

        if(!$subject)
        {
            $this->error('该课程不存在');
        }

        // 获取点赞数组
        $likeArr = explode(',',$subject['likes']);

        // 过滤空的元素
        $likeArr = array_filter($likeArr);
        
        if(in_array($this->LoginAuth['id'],$likeArr))
        {
            foreach($likeArr as $key => $val)
            {
                if($this->LoginAuth['id'] == $val)
                {
                    unset($likeArr[$key]);
                }
            }

            $msg = '取消点赞';
        }else{
            // 走进说明点赞 => 需要把用户id追加likeArr
            // $subject['likes'] .= $this->LoginAuth['id'] . ',';
            // 把元素追加数组
            array_push($likeArr,$this->LoginAuth['id']);
            // echo $subject['likes'];
            // 把数组转成字符串
            // $likeStr = implode(',',$likeArr);
            $msg = '点赞';
        }

        $data = [
            'id' => $subjectid,// 如果这字段是主键 作为更新哪个数据依据
            'likes' => implode(',',$likeArr)
        ];

        $result = $this->SubjectModel->isUpdate(true)->save($data);

        if($result === FALSE)
        {
            $this->error("{$msg}失败");
        }else{
            $this->success("{$msg}成功");
        }
    }
}
